<template>
  <el-dialog
    :modelValue="modelValue"
    @update:model-value="emits('update:modelValue', $event)"
    :title="title"
    width="700"
    id="localedit">
    <div>
      <VarTable
        :model-value="[unsaved]"
        title="局部变量"
        namespace="变量"
        type="VarInit" my
        :no-add="true"/>
      
      <div class="dialog-footer" mt flex>
        <el-button mlauto @click="emits('update:modelValue', false)">取消</el-button>
        <el-button type="primary" @click="confirm()">
          确认
        </el-button>
      </div>
    </div>
    
  </el-dialog>
</template>

<script setup lang="ts">
import _ from 'lodash'
import { tBool, tNum, TypesReceiveLiterial } from '~/models/types';
import type { DataType } from '~/models/types/type';
import { VarInit } from "~/models/data/var_init";
import { oGraph } from '~/models/graph/graph';
import { PNode } from '~/models/graph/node/prototype';
import { PNodeType } from '~/models/graph/node/type';

const props = defineProps<{
  modelValue: boolean,
  target?: VarInit,
}>()

const unsaved = ref(new VarInit('', tNum, tNum.default))

const emits = defineEmits<{
  (e: 'update:modelValue', item: boolean): void
  (e: 'confirm', item: void): void
}>()

watch(() => props.modelValue, val => {
  const newName = uniqueNaming('新变量', oGraph.value?.locals.map(x => x.name) ?? [])
  if (val) {
    if (props.target) {
      lodash.assign(unsaved.value, props.target)
    }
    else {
      unsaved.value = new VarInit('', tNum, tNum.default)
    }
    if (!unsaved.value.name) {
      unsaved.value.name = newName
    }
  }
},{
  immediate: true
})

function confirm() {

  if(!oGraph.value) {
    throw new Error('没有打开函数实现图')
  }
  // 传参了（修改变量 / 按照预设新建）
  if (props.target) {
    // 传参了，但是没挂载（按照预设新建）
    if (oGraph.value.locals.indexOf(props.target) < 0) {
      // 这时首先进行挂载
      oGraph.value.locals.push(props.target)
    }
    // 挂载了（修改变量）
    else {
      // 这时要对图进行检查。如果有任何getter/setter
      // 节点创建了，则需要更新节点确保正确性
      for (const node of oGraph.value.nodes) {
        if (node.prototype.name === props.target.name) {
          if (node.prototype.type === PNodeType.Getter) {
            node.update(PNode.getterFromTGD(unsaved.value))
          }
          else if (node.prototype.type === PNodeType.Setter) {
            node.update(PNode.setterFromTGD(unsaved.value))
          }
        }
      }
    }
    // 同步修改
    props.target.type = unsaved.value.type
    props.target.name = unsaved.value.name
    props.target.initial = unsaved.value.initial
  }
  // 干脆就没传参数（新建变量）
  else {
    oGraph.value.locals.push(unsaved.value)
  }
  

  emits('update:modelValue', false)
  emits('confirm')
}

const title = computed(() => {
  return props.target ? '修改变量声明' : '创建变量' 
})
</script>